// 仪表盘页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化仪表盘数据
    initDashboardData();
    
    // 初始化图表
    initCharts();
    
    // 初始化卡片交互
    initCardInteractions();
    
    // 添加动画效果
    addDashboardAnimations();
});

// 初始化仪表盘数据
function initDashboardData() {
    // 这里可以添加从服务器获取数据的逻辑
    // 目前使用模拟数据
    updateStatsCards();
    updateRecentBookings();
}

// 更新统计卡片数据
function updateStatsCards() {
    // 模拟数据加载动画
    const statNumbers = document.querySelectorAll('.stat-number');
    
    statNumbers.forEach((stat, index) => {
        const targetValue = stat.textContent;
        stat.textContent = '0';
        
        setTimeout(() => {
            animateCounter(stat, 0, parseInt(targetValue.replace(/[^0-9]/g, '')), 1000);
        }, index * 200);
    });
}

// 数字动画函数
function animateCounter(element, start, end, duration) {
    const startTime = performance.now();
    const originalText = element.textContent;
    const suffix = originalText.replace(/[0-9]/g, '').trim();
    
    function updateCount(currentTime) {
        const elapsedTime = currentTime - startTime;
        
        if (elapsedTime < duration) {
            const progress = elapsedTime / duration;
            const easeProgress = easeOutQuart(progress);
            const currentValue = Math.floor(start + (end - start) * easeProgress);
            element.textContent = currentValue + (suffix ? ' ' + suffix : '');
            requestAnimationFrame(updateCount);
        } else {
            element.textContent = end + (suffix ? ' ' + suffix : '');
        }
    }
    
    requestAnimationFrame(updateCount);
}

// 缓动函数
function easeOutQuart(t) {
    return 1 - Math.pow(1 - t, 4);
}

// 更新近期预约
function updateRecentBookings() {
    const bookingCards = document.querySelectorAll('.booking-card');
    
    bookingCards.forEach((card, index) => {
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 300 + index * 200);
    });
}

// 初始化图表
function initCharts() {
    // 在实际项目中，这里可以使用Chart.js或ECharts等图表库
    // 目前使用简单的占位符动画
    createPlaceholderChart();
}

// 创建占位符图表动画
function createPlaceholderChart() {
    const chartPlaceholder = document.querySelector('.chart-placeholder');
    if (!chartPlaceholder) return;
    
    // 创建简单的条形图动画
    const chartContainer = document.createElement('div');
    chartContainer.className = 'simple-bar-chart';
    
    // 设置样式
    Object.assign(chartContainer.style, {
        width: '100%',
        height: '200px',
        display: 'flex',
        alignItems: 'flex-end',
        justifyContent: 'space-around',
        padding: '20px 0',
    });
    
    // 创建条形
    const data = [65, 59, 80, 81, 56, 55, 72];
    const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    
    data.forEach((value, index) => {
        const barGroup = document.createElement('div');
        barGroup.style.display = 'flex';
        flexDirection: 'column';
        alignItems: 'center';
        flex: 1;
        maxWidth: '50px';
        
        const bar = document.createElement('div');
        Object.assign(bar.style, {
            width: '30px',
            backgroundColor: '#1890ff',
            borderRadius: '4px 4px 0 0',
            transition: 'height 1s ease-out',
            height: '0',
            minHeight: '10px',
        });
        
        const label = document.createElement('div');
        label.textContent = days[index];
        label.style.fontSize = '12px';
        label.style.color = '#666';
        label.style.marginTop = '5px';
        
        barGroup.appendChild(bar);
        barGroup.appendChild(label);
        chartContainer.appendChild(barGroup);
        
        // 动画延迟
        setTimeout(() => {
            bar.style.height = value * 2 + 'px';
        }, 500 + index * 100);
    });
    
    // 替换占位符
    chartPlaceholder.innerHTML = '';
    chartPlaceholder.appendChild(chartContainer);
}

// 初始化卡片交互
function initCardInteractions() {
    // 统计卡片交互
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach(card => {
        card.addEventListener('click', function() {
            // 可以添加点击卡片后的交互逻辑
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'translateY(-5px)';
            }, 200);
        });
    });
    
    // 预约卡片交互
    const bookingCards = document.querySelectorAll('.booking-card');
    bookingCards.forEach(card => {
        const buttons = card.querySelectorAll('.btn');
        
        buttons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                
                if (this.textContent.includes('取消')) {
                    if (confirm('确定要取消这个预约吗？')) {
                        showToast('预约已取消', 'success');
                        card.style.opacity = '0.5';
                    }
                } else if (this.textContent.includes('详情')) {
                    // 查看详情逻辑
                    showToast('查看预约详情', 'info');
                }
            });
        });
    });
    
    // 推荐项交互
    const recommendItems = document.querySelectorAll('.recommend-item');
    recommendItems.forEach(item => {
        item.addEventListener('click', function() {
            const text = this.querySelector('span').textContent;
            showToast(`推荐区域: ${text}`, 'info');
            // 可以跳转到对应的座位选择页面
        });
    });
}

// 添加仪表盘动画效果
function addDashboardAnimations() {
    // 页面滚动动画
    const animateOnScroll = () => {
        const elements = document.querySelectorAll('.stat-card, .booking-card, .dashboard-card');
        
        elements.forEach(element => {
            const elementTop = element.getBoundingClientRect().top;
            const elementVisible = 150;
            
            if (elementTop < window.innerHeight - elementVisible) {
                element.classList.add('animated');
            }
        });
    };
    
    // 初始设置
    document.querySelectorAll('.stat-card, .booking-card, .dashboard-card').forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    });
    
    // 添加滚动事件
    window.addEventListener('scroll', debounce(animateOnScroll, 20));
    
    // 初始触发一次
    animateOnScroll();
}

// 模拟数据刷新
function refreshDashboardData() {
    // 模拟数据加载
    const statsContainer = document.querySelector('.stats-grid');
    statsContainer.style.opacity = '0.6';
    
    setTimeout(() => {
        // 更新随机数据
        const statNumbers = document.querySelectorAll('.stat-number');
        const randomValues = [
            Math.floor(Math.random() * 5) + 1,
            Math.floor(Math.random() * 10) + 3,
            Math.floor(Math.random() * 50) + 20,
            Math.floor(Math.random() * 200) + 100
        ];
        
        statNumbers.forEach((stat, index) => {
            const suffix = stat.textContent.replace(/[0-9]/g, '').trim();
            stat.textContent = randomValues[index] + (suffix ? ' ' + suffix : '');
        });
        
        statsContainer.style.opacity = '1';
        showToast('数据已刷新', 'success');
    }, 800);
}

// 添加定时刷新（仅演示用）
setInterval(refreshDashboardData, 30000); // 每30秒刷新一次

// 导出仪表盘数据
function exportDashboardData() {
    const data = [
        ['统计项', '数值'],
        ['今日预约', document.querySelector('.stat-card:nth-child(1) .stat-number').textContent],
        ['本周预约', document.querySelector('.stat-card:nth-child(2) .stat-number').textContent],
        ['累计学习时长', document.querySelector('.stat-card:nth-child(3) .stat-number').textContent],
        ['积分', document.querySelector('.stat-card:nth-child(4) .stat-number').textContent]
    ];
    
    const filename = `dashboard-data-${formatDate(new Date(), 'YYYY-MM-DD')}.csv`;
    exportToCSV(data, filename);
}

// 快速预约功能
function quickBook() {
    showToast('快速预约功能即将开放', 'info');
    // 可以跳转到座位选择页面并预填一些选项
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + R 刷新数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            refreshDashboardData();
        }
        
        // Ctrl/Cmd + E 导出数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
            e.preventDefault();
            exportDashboardData();
        }
        
        // Ctrl/Cmd + B 快速预约
        if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
            e.preventDefault();
            quickBook();
        }
    });
}

// 初始化键盘快捷键
addKeyboardShortcuts();

// 监听窗口大小变化，重新调整图表
window.addEventListener('resize', debounce(() => {
    const chartContainer = document.querySelector('.simple-bar-chart');
    if (chartContainer) {
        chartContainer.remove();
        createPlaceholderChart();
    }
}, 300));

// 暗色模式切换（如果需要）
function toggleDarkMode() {
    document.body.classList.toggle('dark-mode');
    const isDarkMode = document.body.classList.contains('dark-mode');
    
    // 保存用户偏好
    localStorage.setItem('darkMode', isDarkMode);
    showToast(isDarkMode ? '已切换到暗色模式' : '已切换到亮色模式', 'info');
}

// 检查用户暗色模式偏好
function checkDarkModePreference() {
    const savedMode = localStorage.getItem('darkMode');
    if (savedMode === 'true' || 
        (!savedMode && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.body.classList.add('dark-mode');
    }
}